<?php

/**
 * @Author: liu
 * @Date:   2018-02-05 11:46:54
 * @Last Modified by:   liu
 * @Last Modified time: 2018-09-11 09:44:02
 * 用于订货单的逻辑
 */

class ScsPlanOrderController extends BaseController {
    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-02-05T13:43:50+0800
     * @return   [type]                   [description]
     * 根据需求单列表创建订货单
     */
    public function purchase_create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'purchase_order_id' => 'required',//采购单id
                'suppller_id' => 'required',//供应商id
                'pay_type' => 'required|in:1,0',//0现金 1定期
                'tax' => 'required|in:1,2',//是否含税(1:含税;2:不含税;)
                'logistics_freight' => 'required|in:1,2',//物流运费(1:含运费;2:不含运费;)
                'args' => 'required',//[{"product_id":1,"tax_purchase_price":10,"no_tax_purchase_price":10}]
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $purchase_order_id = Input::get('purchase_order_id');
            $suppller_id = Input::get('suppller_id');
            $pay_type = Input::get('pay_type');
            $args = Input::get('args');
            $tax = Input::get('tax');
            $logistics_freight = Input::get('logistics_freight');
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            if (!in_array($pay_type, [1, 0]) || !in_array($tax, [1, 2]) || !in_array($logistics_freight, [1, 2])) {
                $response = Lang::get('scs_error.maintenance_supplier_pay_tax_freight_error_130001');
                break;
            }
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $response = DB::transaction(function() use ($sc_user,$purchase_order_id,$suppller_id,$pay_type,$args, $tax, $logistics_freight){
                $pmo=PMSOrder::find($purchase_order_id);
	            if(is_null($pmo)||$pmo->shop_id!=$sc_user->shop_id||$pmo->source==2) {
	                return Lang::get("scs_error.purchase_order_notexit_65000");
	            }
	            if ($pmo->status!=1) {//不是新建和驳回不能修改采购时间
	                return Lang::get("scs_error.purchase_order_status_65001");
	            }
	            if ($pmo->type!=2) {//只有自采的才需要自己创建 订货单
                    return Lang::get("scs_error.purchase_order_type_error_65005");
                }
                $ms=MaintenanceSupplier::find($suppller_id);
                if(is_null($ms)||$ms->status!=1||$ms->purchase_status!=1){
                	return Lang::get("scs_error.supplier_error_10013");
                }
                /**
                 * step 1 生成订货单
                 * @var [type]
                 */
                $plan_code =Common::createOrderId(); //'订货单号',
                $plan_order = new PMSPlanOrder();
                $plan_order->plan_code = $plan_code;
                $plan_order->supplier_id = $suppller_id;
                $plan_order->pay_type= $pay_type;
                $plan_order->address= $sc_user->shop->address;
                $plan_order->all_num= $pmo->all_num;
                $plan_order->status = 2;
                $plan_order->type = 2; //门店能提并订货的只有 自采类型的
                $plan_order->created_type = 1;
                $plan_order->created_by =$sc_user->id;
                $plan_order->updated_type = 1;
                $plan_order->updated_by =$sc_user->id;
                $plan_order->submit_at = date("Y-m-d H:i:s");
                $plan_order->save();
                /**
                 * step 1 生成收货单
                 * @var [type]
                 */
                $receive_code =Common::createOrderId(); //'收货单id',
                $receive_order = new PMSReceiveOrder();
                $receive_order->receive_code=$receive_code;
                $receive_order->plan_code = $plan_code;
                $receive_order->shop_id = $sc_user->shop_id;
                $receive_order->supplier_id = $suppller_id;
                $receive_order->pay_type= $pay_type;
                $receive_order->tax= $tax;                  //收货单添加是否含税
                $receive_order->logistics_freight= $logistics_freight;      //收货单添加物流运费
                $receive_order->address= $sc_user->shop->address;
                $receive_order->all_num= $pmo->all_num;
                $receive_order->status = 2;
                $receive_order->created_type = 1;
                $receive_order->created_by =$sc_user->id;
                $receive_order->updated_type = 1;
                $receive_order->updated_by =$sc_user->id;
                $receive_order->save();

                /**
                 * step 2 检查采购单的各项 生成 订货单和 收货单的详情
                 * @var [type]
                 */
                $ids=$args?json_decode($args,1):array();
                $total_amount=0;
                foreach ($ids as $_id) {
                    $pmsop=PMSOrderProducts::find($_id["product_id"]);
                    if(is_null($pmsop)||$pmsop->status!=1||$pmsop->pms_code!=$pmo->pms_code){
                    	DB::rollback();
                    	return Lang::get("scs_error.purchase_order_product_notexit_65002");
                    }
                    // if($pmsop->quotations_number<3){
                    //     DB::rollback();
                    //     return Lang::get("scs_error.purchase_order_product_number_65008");
                    // }
                    /**
                     * step 3 生成订货单详情
                     * @var PMSPlanProducts
                     */
                    $pmspp=new PMSPlanProducts();
                    $pmspp->pms_code=$pmsop->pms_code;
                    $pmspp->order_products_id=$pmsop->id;
                    $pmspp->plan_code=$plan_code;
                    $pmspp->product_id=$pmsop->product_id;
                    $pmspp->pid=0;
					$pmspp->status=3;//状态为 3已定货
                    $pmspp->all_num=$pmsop->all_num;//采购数量
                    $pmspp->last_num=$pmsop->all_num;//剩余清点数量
                    $pmspp->ready_num=0;
                    $pmspp->tax_purchase_price=$_id["tax_purchase_price"]*100;
                    $pmspp->no_tax_purchase_price=$_id["no_tax_purchase_price"]*100;
                    $pmspp->is_split=0;  
                    $pmspp->from_key=$sc_user->shop->name; 
                    $pmspp->save();
                    /**
                     * step 4 生成收货单详情
                     * @var PMSReceiveProducts
                     */
                    $pmsrp=new PMSReceiveProducts();
                    $pmsrp->receive_code=$receive_code; //收货单号
                    $pmsrp->pms_code=$pmsop->pms_code;  //采购单号
                    $pmsrp->plan_products_id=$pmspp->id;//记录该条收货单 来源的订货单id
                    $pmsrp->plan_code=$plan_code;       //记录订货单id
                    $pmsrp->product_id=$pmsop->product_id;
                    // $pmsrp->pid=0;
                    $pmsrp->status=2; //状态为  2待收货  
                    $pmsrp->all_num=$pmsop->all_num;//采购数量
                    $pmsrp->last_num=$pmsop->all_num;//剩余清点数量
                    $pmsrp->ready_num=0;
                    $pmsrp->tax_purchase_price=$_id["tax_purchase_price"]*100;
                    $pmsrp->no_tax_purchase_price=$_id["no_tax_purchase_price"]*100;
                    // $pmsrp->is_split=0;  
                    $pmsrp->from_key=$sc_user->shop->name; 
                    $pmsrp->save();
                    
                    /**
                     * step 5 修改采购单的已经采购数量 采购中数量和未满足数量
                     * @var [type]
                     */
                    $pmsop->ready_num=$pmsop->all_num;//已采购数量
                    $pmsop->last_num=0;//采购中数量
                    $pmsop->error_num=0;//未满足数量 也就是异常数量
                    $pmsop->save();
                    /**
                     * step 6 计算已经处理的采购单项目数量
                     * @var [type]
                     */
                    $total_amount+=$pmsop->all_num;
                }        
                /**
                 * step 7 修改订货单和收货单的采购数量
                 */
                PMSPlanOrder::where("plan_code",$plan_code)->update(array("all_num"=>$total_amount));
                PMSReceiveOrder::where("receive_code",$receive_code)->update(array("all_num"=>$total_amount));
                /**
                 * step 8 修改采购单的状态,已采购数量，未满足数量 并记录流水
                 */
                $pms_order_flow = new PMSOrderFlow();
                $pms_order_flow->pms_code = $pmo->pms_code;
                $pms_order_flow->status =5;
                $pms_order_flow->operation =7;
                $pms_order_flow->created_by =$sc_user->id;
                $pms_order_flow->created_type = 1;
                $pms_order_flow->save();

                $dz=SCUser::where("shop_id",$sc_user->shop_id)->where("status",1)->where("title",1)->first();
                $pmo->ready_num=$total_amount;
                $pmo->approve_type=1;
                $pmo->approve_by=isset($dz->id)?$dz->id:0;
                $pmo->status=5;
                $pmo->tax = $tax;
                $pmo->regular_pay = $pay_type;
                $pmo->logistics_freight = $logistics_freight;
                $pmo->save();
                return array('code' => 0, 'msg' => 'ok', 'result' => array("plan_order_id"=>$plan_code));
            });           
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "plan_order", "event" => "purchase_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 
    
    
    /**
     * @Author:          zk
     * @DateTime:        18-5-14 下午3:00
     * @Description:     采购询价  直接添加订货单 或者 购物车批量添加订货单
     * @param string $token     用户token
     * @param string $ids       购物车id串 [ 多个值用英文逗号连接 ]  例如:  13 或者 13,14
     * @param string $args      参数字符串  例如:  [{"supplier_id":"526","regular_pay":"1","item_list":[{"id":13,"supply_item_id":214970,"num":"1.00","price":1150}]}]
     * regular_pay 支付方式（0：现金结算；1：定期挂账；）；price 【传递经销商平台报价】价格单位 分
     * @link http://api.anhui.com/v1/scs/planorder/addPlanOrder?token=5eeb35ca397717286cf148c2189c63f0
     * @link http://api.anhui.com/v1/scs/planorder/addPlanOrder?token=5eeb35ca397717286cf148c2189c63f0&ids=13&args=[{"supplier_id":"526","regular_pay":"1","item_list":[{"id":13,"supply_item_id":214970,"num":"1.00","price":1150}]}]
     */
    public function addPlanOrder() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'args' => 'required',
                'ids' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user = $this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $shop_id = $sc_user->shop_id;
            $admin_id = $sc_user->id;
            
            $check_res = PMSReceivesAddress::checkShopDefaultAddress($shop_id, $admin_id);  //校验门店默认收货地址
            if(!$check_res){
                $response = Lang::get("scs_error.order_default_address_error_400141");
                break;
            }
            $address_info = PMSReceivesAddress::getShopDefaultAddress($shop_id);    //默认收货地址信息
            if(!$address_info){
                $response = Lang::get("scs_error.order_default_address_error_400142");
                break;
            }
            $args = Input::get('args');
            $ids = Input::get('ids');
            $args_arr = json_decode($args, TRUE);   //参数数组
            $id_arr = explode(',', $ids);           //购物车信息id数组
            
            
            //查询的时候需要将 对应的耗材id、经销商id 转换为 erp id
            $select_arr = [
                'pms_shopping_car.id', 'pms_shopping_car.shop_id', 'pms_shopping_car.supplier_id', 
                'pms_shopping_car.supply_item_id', 'pms_shopping_car.num', 'pms_shopping_car.price AS car_price',
                'supply_item.name AS supply_item_name', 'supply_item.erp_id AS item_erp_id',
                'maintenance_supplier.name AS supplier_name', 'maintenance_supplier.erp_id AS supplier_erp_id', 
                'maintenance_supplier.regular_pay',
            ];
            $list = DB::table('pms_shopping_car')
                    ->leftJoin('supply_item', 'pms_shopping_car.supply_item_id', '=', 'supply_item.id')
                    ->leftJoin('maintenance_supplier', 'pms_shopping_car.supplier_id', '=', 'maintenance_supplier.id')
                    ->where('pms_shopping_car.shop_id', $shop_id)
                    ->where('pms_shopping_car.status', 1)
                    ->whereIn('pms_shopping_car.id', $id_arr)
                    ->select($select_arr)
                    ->get();
            $item_erp_arr = [];     //耗材erpid数组
            $item_erp_key_arr = []; //耗材id为key，对应的erpid为value
            $supplier_erp_arr = []; //供应商erpid数组
            $supplier_erp_key_arr = []; //供应商id为key，对应的erpid为value
            if($list){
                foreach ($list as $v) {
                    $item_erp_arr[] = $v->item_erp_id;
                    $item_erp_key_arr[$v->supply_item_id] = $v->item_erp_id;
                    $supplier_erp_arr[] = $v->supplier_erp_id;
                    $supplier_erp_key_arr[$v->supplier_id] = $v->supplier_erp_id;
                }
                $item_erp_arr = array_unique($item_erp_arr);
                $supplier_erp_arr = array_unique($supplier_erp_arr);
                //查询经销商平台 耗材报价和库存
                $query_price_list = GYSQueryPrice::getQueryPriceList($item_erp_arr, $supplier_erp_arr, $shop_id, 2);
                if(empty($query_price_list)){
                    //查询出的耗材报价、库存 为空 返回提示
                    $response = Lang::get("scs_error.shopping_query_pirce_error_65013");
                    break;
                }
            } else {
                //未查询到有效的购物车信息
                $response = Lang::get("scs_error.shopping_car_error_65015");
                break;
            }
            
            $plan_order_ids = '';   //订单完成的订单id串 # 分隔
            //以下为开始下单
            foreach ($args_arr as $v) {
                $all_num = 0;   //采购总数量
                $temp_item_arr = [];    //经销商平台下单时的耗材信息数组
                foreach ($v['item_list'] as $_item_list) {
                    $all_num = $all_num + $_item_list['num'];
                    $temp_item_arr[] = [
                        'item_id' => $item_erp_key_arr[$_item_list['supply_item_id']], 
                        'amount' => $_item_list['price'] / 100,     //转换成 元
                        'number' => intval($_item_list['num']),
                    ];
                }
                //经销商平台下单
                $gys_info = GYSQueryPrice::createOrder($shop_id, $supplier_erp_key_arr[$v['supplier_id']], $v['regular_pay'], $temp_item_arr, $address_info);
                if($gys_info['code'] == 0){
                    $response = DB::transaction(function() use (&$plan_order_ids, $gys_info, $v, $all_num, $address_info, $shop_id, $admin_id, $sc_user){
                        $success_id_arr = [];  //成功下单的购物车 id
                        //  1、 生成订货单
                        $plan_code = Common::createOrderId(); //'订货单号',
                        $plan_order = new PMSPlanOrder();
                        $plan_order->plan_code = $plan_code;
                        $plan_order->supplier_id = $v['supplier_id'];
                        $plan_order->pay_type = $v['regular_pay'];
                        $plan_order->address = $address_info->address;
                        $plan_order->other_order_code = $gys_info['order'];      //第三方单号[经销商平台单号]
                        $plan_order->all_num = $all_num;
                        $plan_order->status = 2;    //1:拼货中;2:待收货;3:已收货;
                        $plan_order->type = 1;    //1：集采  2：零采
                        $plan_order->operation_type = 2;    //下单方式 (1:原有方式下单;2:门店询价下单;)
                        $plan_order->shop_id = $shop_id;
                        $plan_order->created_type = 1;
                        $plan_order->created_by = $admin_id;
                        $plan_order->updated_type = 1;
                        $plan_order->updated_by = $admin_id;
                        $plan_order->submit_at = date('Y-m-d H:i:s', time());
                        $plan_order->save();
                        $plan_order_ids .= $plan_code.'#';  //订单完成的订单id串 # 分隔
                                
                        //  2、生成收货单
                        $receive_code = Common::createOrderId(); //'收货单id',
                        $receive_order = new PMSReceiveOrder();
                        $receive_order->receive_code = $receive_code;
                        $receive_order->plan_code = $plan_code;
                        $receive_order->shop_id = $shop_id;
                        $receive_order->supplier_id = $v['supplier_id'];
                        $receive_order->pay_type = $v['regular_pay'];
                        $receive_order->address = $address_info->address;
                        $receive_order->other_order_code = $gys_info['order'];      //第三方单号[经销商平台单号]
                        $receive_order->all_num = $all_num;
                        $receive_order->status = 2; //1:拼货中;2:待收货;3:已收货;
                        $receive_order->created_type = 1;
                        $receive_order->created_by = $admin_id;
                        $receive_order->updated_type = 1;
                        $receive_order->updated_by = $admin_id;
                        $receive_order->save();

                        // 3、生成 订货单详情 和 收货单详情
                        foreach ($v['item_list'] as $_item_list) {
                            //生成订货单详情
                            $pmspp = new PMSPlanProducts();
                            //$pmspp->pms_code = '';          //采购单单号
                            //$pmspp->order_products_id = ''; //来源于哪个采购单的商品
                            $pmspp->plan_code = $plan_code;
                            $pmspp->product_id = $_item_list['supply_item_id'];
                            $pmspp->pid = 0;
                            $pmspp->status = 3; //状态为 3已定货
                            $pmspp->all_num = $_item_list['num'];    //采购数量
                            $pmspp->last_num = $_item_list['num'];   //剩余清点数量
                            $pmspp->ready_num = 0;
                            $pmspp->tax_purchase_price = $_item_list['price'];
                            $pmspp->no_tax_purchase_price = $_item_list['price'];
                            $pmspp->is_split = 0;  
                            $pmspp->from_key = $sc_user->shop->name;
                            $pmspp->save();

                            //生成收货单详情
                            $pmsrp = new PMSReceiveProducts();
                            $pmsrp->receive_code = $receive_code; //收货单号
                            $pmsrp->pms_code = '';  //采购单号
                            $pmsrp->plan_products_id = $pmspp->id;//记录该条收货单 来源的订货单id
                            $pmsrp->plan_code = $plan_code;       //记录订货单id
                            $pmsrp->product_id = $_item_list['supply_item_id'];
                            $pmsrp->status = 2; //状态为  2待收货  
                            $pmsrp->all_num = $_item_list['num'];   //采购数量
                            $pmsrp->last_num = $_item_list['num'];  //剩余清点数量
                            $pmsrp->ready_num = 0;
                            $pmsrp->tax_purchase_price = $_item_list['price'];
                            $pmsrp->no_tax_purchase_price = $_item_list['price'];
                            $pmsrp->from_key = $sc_user->shop->name; 
                            $pmsrp->save();
                            
                            $success_id_arr[] = $_item_list['id'];  //成功下单的购物车 id
                        }
                        
                        // 4、订货单与经销商平台 单号对照表 数据添加
                        $pmspoc = new PMSPlanOrderContrast();
                        $pmspoc->plan_code = $plan_code;    //订货单号
                        $pmspoc->shop_id = $shop_id;    //门店id
                        $pmspoc->gys_plan_code = $gys_info['order'];    //经销商平台 订货单号
                        $pmspoc->status = 1;    //状态(1:正常;2:已删除;)
                        $pmspoc->created_at = date('Y-m-d H:i:s', time());
                        $pmspoc->created_by = $admin_id;
                        $pmspoc->save();
                        
                        // 5、 购物车状态修改
                        $car_data['status'] = 3;     //状态(1:正常;2:已删除;3:已下单;)
                        $car_data['updated_at'] = date('Y-m-d H:i:s', time());
                        $car_data['updated_by'] = $admin_id;
                        $car_data['plan_order_id'] = $plan_code;
                        if(!empty($success_id_arr)){
                            DB::table('pms_shopping_car')->where('shop_id', $shop_id)->where('status', 1)
                                    ->whereIn('id', $success_id_arr)->update($car_data);   
                        }
                    });
                } else {
                    //经销商平台 下单失败 
                    Log::info("error", array(
                        "system" => "scs" ,
                        "event" => "addPlanOrder", 
                        //"msg" => "经销商平台下单失败" ,
                        "msg" => $gys_info['msg'],
                        "shop_id" => $shop_id,
                        "supplier_id" => $v['supplier_id'],
                        "pay_type" => $v['regular_pay'],
                        "item_list" => json_encode($temp_item_arr),
                    ));
                    //$response = Lang::get("scs_error.shopping_car_add_order_error_65017");
                    $response = [
                        'code' => $gys_info['code'],
                        'msg' => $gys_info['msg'],
                    ];
                    return $response;
                }
            }
            
            return array('code' => 0, 'msg' => 'ok', 'result' => array("plan_order_ids" => $plan_order_ids));
        }while(false);
        
        Log::info("info", array("system" => "scs" ,"event" => "addPlanOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    
}